﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

using System.IO;

using PlanningGIS.Framework;
using ESRI.ArcGIS.Carto;
using DevComponents.DotNetBar;
using PlanningGIS.Win.Controls;
using PlanningGIS.Framework.Config;
using PlanningGIS.Util.Convertor;
using PlanningGIS.Framework.Rule;
using PlanningGIS.Util.Log;
using ESRI.ArcGIS.Geodatabase;

namespace PlanningGIS.TocContextMenu.form
{
    public partial class FrmSymbolSetting : Office2007Form
    {
        private string PATH = AppConfig.StylePath;
        private IStatusBar m_pStatusBar;

        private List<IFeatureLayer> pFeatLyrs;

        public FrmSymbolSetting(IStatusBar value)
        {
            PATH = AppConfig.StylePath;

            m_pStatusBar = value;
            InitializeComponent();
        }

        public List<IFeatureLayer> FeatureLayers
        {
            set { pFeatLyrs = value; }
        }

        private void FrmSymbolSetting_Load(object sender, EventArgs e)
        {
            #region 初始化符号库文件

            DirectoryInfo dir = new DirectoryInfo(PATH);
            FileInfo[] fileInfos = dir.GetFiles("*.style");

            cboSymbolStyle.Items.Clear();

            if (fileInfos.Length > 0)
            {
                for (int i = 0; i < fileInfos.Length; i++)
                {
                    FileInfo fileInfo = fileInfos[i];
                    string fileName = fileInfo.Name;
                    cboSymbolStyle.Items.Add(fileName);
                }

                cboSymbolStyle.SelectedIndex = 0;
                cboSymbolStyle.Text = AppConfig.SystemConfig.符号化.默认符号库;
            }

            #endregion

            #region 初始化旋转角度

            cboAngleField.Items.Clear();

            string[] angleFields = AppConfig.SystemConfig.符号化.角度字段.Split(';');
            //string angleField = "";
            for (int i = 0; i < angleFields.Length; i++)
            {
                string temp = angleFields[i];

                if (temp.Trim() == "") continue;
                
                ////第一个字符为空格（" "）的为当前所选的字段
                //if (temp.Length > 0 && temp.Substring(0, 1) == " ")
                //{
                //    angleField = temp.Trim();
                //}

                cboAngleField.Items.Add(temp.Trim());
            }

            if (cboAngleField.Items.Count > 0)
            {
                cboAngleField.SelectedIndex = 0;
                //if (angleField != "") cboAngleField.Text = angleField;
            }


            if (StringHelper.CanConvert2Int(AppConfig.SystemConfig.符号化.旋转方式))
            {
                int symbolRotationType = Int16.Parse(AppConfig.SystemConfig.符号化.旋转方式);
                if (symbolRotationType == 0)
                    cboSymbolRotationType.SelectedIndex = 0;
                else
                    cboSymbolRotationType.SelectedIndex = 1;
            }

            #endregion

            #region 初始化规则列表

            cboRuleName.Items.Clear();
            for (int i = 0; i < RuleConfig.DataBuilding.BuildingRules.Count; i++)
            {
                cboRuleName.Items.Add(RuleConfig.DataBuilding.BuildingRules[i].RuleName);
            }

            if (cboRuleName.Items.Count > 0)
            {
                cboRuleName.SelectedIndex = 0;
                cboRuleName.Text = AppConfig.SystemConfig.符号化.默认规则;
            }

            #endregion

            #region 初始化符号化字段

            cboSymbolField.Items.Clear();
            cmbField1.Items.Clear();
            cmbField2.Items.Clear();
            cmbField3.Items.Clear();

            string[] symbolFields = AppConfig.SystemConfig.符号化.符号化字段.Split(';');
            //string symbolField = "";
            for (int i = 0; i < symbolFields.Length; i++)
            {
                string temp = symbolFields[i];

                if (temp.Trim() == "") continue;

                ////第一个字符为空格（" "）的为当前所选的字段
                //if (temp.Length > 0 && temp.Substring(0, 1) == " ")
                //{
                //    symbolField = temp.Trim();
                //}

                cboSymbolField.Items.Add(temp.Trim());
            }

            if (cboSymbolField.Items.Count > 0)
            {
                cboSymbolField.SelectedIndex = 0;
                //if (symbolField != "") cboSymbolField.Text = symbolField;
            }

            if (pFeatLyrs != null && pFeatLyrs.Count == 1) 
            {
                IFeatureClass pFcl = pFeatLyrs[0].FeatureClass;
                IFields pFds = pFcl.Fields;
                for (int i = 0; i < pFds.FieldCount; i++)
                {
                    IField pFd = pFds.Field[i];
                    if (pFd.Type != esriFieldType.esriFieldTypeGeometry)
                    {
                        cmbField1.Items.Add(pFd.Name);
                        cmbField2.Items.Add(pFd.Name);
                        cmbField3.Items.Add(pFd.Name);
                    }
                }
            }

            #endregion

            //txtField2.Enabled = false;
            //txtField3.Enabled = false;
            cmbField2.Enabled = false;
            cmbField3.Enabled = false;
        }

        private void btnOpen_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFileDialogStyle = new OpenFileDialog();
            openFileDialogStyle.Multiselect = false;
            openFileDialogStyle.RestoreDirectory = true;
            openFileDialogStyle.Title = "选择符号库";
            openFileDialogStyle.Filter = "符号库|*.Style";
            if (openFileDialogStyle.ShowDialog() == DialogResult.OK)
            {
                try
                {
                    File.Copy(openFileDialogStyle.FileName, PATH + "\\" + openFileDialogStyle.SafeFileName);
                    cboSymbolStyle.Items.Add(openFileDialogStyle.SafeFileName);
                }
                catch (Exception ex)
                {
                    DialogResult dr = MsgHelper.ShowYesOrNoQueryMsgBox(ex.Message + "是否需要用新的符号库替换已有符号库？");
                    if (dr == DialogResult.Yes)
                    {
                        try
                        {
                            File.Copy(openFileDialogStyle.FileName, PATH + "\\" + openFileDialogStyle.SafeFileName, true);
                        }
                        catch (Exception ex2)
                        {
                            LogHelper.WriteLog(ex2);
                            return;
                        }
                    }
                }
                finally
                {
                    cboSymbolStyle.Text = openFileDialogStyle.SafeFileName;
                }
            }

        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            DialogResult = DialogResult.Cancel;
            this.Close();
        }

        private void btnOK_Click(object sender, EventArgs e)
        {
            try
            {
                if (cboSymbolStyle.Text == "")
                {
                    MsgHelper.ShowInfomationMsgbox("请设置符号库文件！");
                    return;
                }
                AppConfig.SystemConfig.符号化.默认符号库 = cboSymbolStyle.Text;

                if (cboAngleField.Text == "")
                {
                    MsgHelper.ShowInfomationMsgbox("请设置旋转角度字段！");
                    return;
                }

                this.Cursor = Cursors.WaitCursor;

                List<string> angleFields = new List<string>();
                angleFields.Add(cboAngleField.Text);
                foreach (object obj in cboAngleField.Items)
                {
                    if (angleFields.Contains(obj.ToString()) == false)
                        angleFields.Add(obj.ToString());
                }
                string angleField = "";
                foreach (string temp in angleFields)
                {
                    if (temp.Trim() == "") continue;
                    //if (temp == cboAngleField.Text)
                    //{
                    //    angleField = angleField + " " + temp + ";";
                    //}
                    //else
                    //{
                        angleField = angleField + temp + ";";
                    //}
                }
                AppConfig.SystemConfig.符号化.角度字段 = angleField.TrimEnd(':');

                AppConfig.SystemConfig.符号化.旋转方式 = cboSymbolRotationType.SelectedIndex.ToString();
                
                switch (tabControl1.SelectedTabIndex)
                {
                    case 0:
                        if (cboRuleName.Text == "")
                        {
                            MsgHelper.ShowInfomationMsgbox("请设置符号化规则！");
                            return;
                        }
                        AppConfig.SystemConfig.符号化.默认规则 = cboRuleName.Text;

                        if (cboSymbolField.Text == "")
                        {
                            MsgHelper.ShowInfomationMsgbox("请设置符号化字段！");
                            return;
                        }
                        List<string> symbolFields = new List<string>();
                        symbolFields.Add(cboSymbolField.Text);
                        foreach (object obj in cboSymbolField.Items)
                        {
                            if (symbolFields.Contains(obj.ToString()) == false)
                                symbolFields.Add(obj.ToString());
                        }
                        string symbolField = "";
                        foreach (string temp in symbolFields)
                        {
                            if (temp.Trim() == "") continue;
                            //if (temp == cboSymbolField.Text)
                            //{
                            //    symbolField = symbolField + " " + temp + ";";
                            //}
                            //else
                            //{
                                symbolField = symbolField + temp + ";";
                            //}
                        }
                        AppConfig.SystemConfig.符号化.符号化字段 = symbolField.TrimEnd(':');

                        SymbolizeUtility.SymbolizeLyrsByRule(pFeatLyrs, m_pStatusBar, PATH + "\\" + cboSymbolStyle.Text, cboAngleField.Text,
                            (esriSymbolRotationType)cboSymbolRotationType.SelectedIndex, cboRuleName.Text, cboSymbolField.Text,chkUniqueOnly.Checked);
                        break;

                    case 1:
                        if (cmbField1.Text.Trim() == "")
                        {
                            MsgHelper.ShowInfomationMsgbox("请设置唯一字段！");
                            return;
                        }

                        string field1 = "";
                        string field2 = "";
                        string field3 = "";
                        string conStr = "";

                        field1 = cmbField1.Text.Trim();
                        field2 = cmbField2.Text.Trim();

                        if (field2 != "")
                        {
                            field3 = cmbField3.Text.Trim();
                        }

                        conStr = txtConnect.Text;

                        SymbolizeUtility.SymbolizeLyrsByUniqueFields(pFeatLyrs, m_pStatusBar, PATH + "\\" + cboSymbolStyle.Text, cboAngleField.Text,
                            (esriSymbolRotationType)cboSymbolRotationType.SelectedIndex, field1, field2, field3, conStr);
                        break;

                    default:
                        break;
                }

                ConfigHelper.SaveObject<PlanningGIS.Framework.Config.SystemConfig>(AppConfig.SystemConfig);
                DialogResult = DialogResult.OK;

                this.Close();
            }
            catch (Exception ex)
            {
                MsgHelper.ShowWarningMsgbox("符号化失败：" + ex.Message);
            }
            finally
            {
                this.Cursor = Cursors.Default;
            }

        }

        //private void txtField1_TextChanged(object sender, EventArgs e)
        //{
        //    txtField2.Enabled = !(txtField1.Text == "");
        //    if (txtField2.Enabled == false) txtField3.Enabled = false;
        //}

        //private void txtField2_TextChanged(object sender, EventArgs e)
        //{
        //    txtField3.Enabled = !(txtField2.Text == "");
        //}

        private void cboSymbolStyle_SelectedIndexChanged(object sender, EventArgs e)
        {
            SymbolizeUtility.markSymbols = null;
            SymbolizeUtility.lineSymbols = null;
            SymbolizeUtility.fillSymbols = null;
        }

        private void cmbField1_TextChanged(object sender, EventArgs e)
        {
            cmbField2.Enabled = !(cmbField1.Text == "");
            if (cmbField2.Enabled == false) cmbField3.Enabled = false;
        }

        private void cmbField2_TextChanged(object sender, EventArgs e)
        {
            cmbField3.Enabled = !(cmbField2.Text == "");
        }
    }
}
